 //控制层 
app.controller('goodsController' ,function($scope,$controller,$location,uploadService,goodsService,itemCatService,typeTemplateService){
	
	$controller('baseController',{$scope:$scope});//继承
	
    //读取列表数据绑定到表单中  
	$scope.findAll=function(){
		goodsService.findAll().success(
			function(response){
				$scope.list=response.list;
			}			
		);
	}    
	
	//分页
	$scope.findPage=function(page,rows){			
		goodsService.findPage(page,rows).success(
			function(response){
				$scope.list=response.list;
				$scope.paginationConf.totalItems=response.total;//更新总记录数
			}			
		);
	}
	
	//查询实体 
	$scope.findOne=function(){
        var id= $location.search()['id']; //获取页面上传过来的参数 id;search()未$location服务自带的方法,获得所有参数封装为数组

		if (id == null) { //如果没有参数,直接返回
			return;
		}
		goodsService.findOne(id).success(
			function(response){
				$scope.entity= response;

				//向富文本编辑器中添加商品介绍内容
				editor.html($scope.entity.goodsDesc.introduction);

				//显示商品图片
				if ($scope.entity.goodsDesc.itemImages != null){
                    $scope.entity.goodsDesc.itemImages=JSON.parse($scope.entity.goodsDesc.itemImages);
                } else {
                    $scope.entity.goodsDesc.itemImages=[];
				}

                //显示扩展属性
				$scope.entity.goodsDesc.customAttributeItems=JSON.parse($scope.entity.goodsDesc.customAttributeItems);

				//规格
                $scope.entity.goodsDesc.specificationItems=JSON.parse($scope.entity.goodsDesc.specificationItems);

                //SKU列表规格列转换
                for (var i = 0; i < $scope.entity.itemList.length; i++) {
                	$scope.entity.itemList[i].spec=JSON.parse($scope.entity.itemList[i].spec);
                }
			}
		);				
	}
	
	//保存 (添加,修改)
    $scope.save=function(){
        //提取文本编辑器的值
        $scope.entity.goodsDesc.introduction=editor.html();
        var serviceObject;//服务层对象
        if($scope.entity.goods.id!=null){//如果有ID
            serviceObject=goodsService.update( $scope.entity ); //修改
        }else{
            serviceObject=goodsService.add( $scope.entity  );//增加
        }
        serviceObject.success(
            function(response){
                if(response.success){
                    alert('保存成功');
                    $scope.entity={};
                    editor.html("");
                    location.href='goods.html';
                }else{
                    alert(response.message);
                }
            }
        );
    }

	
	 
	//批量删除 
	$scope.dele=function(){			
		//获取选中的复选框
		if (confirm("是否确认删除？")) {
            goodsService.dele( $scope.selectIds ).success(
                function(response){
                    if(response.success){
                        $scope.reloadList();//刷新列表
                        $scope.selectIds=[];
                    }
                }
            );
		}
	}
	
	$scope.searchEntity={};//定义搜索对象 
	
	//搜索
	$scope.search=function(page,rows){			
		goodsService.search(page,rows,$scope.searchEntity).success(
			function(response){
				$scope.list=response.list;
				$scope.paginationConf.totalItems=response.total;//更新总记录数
			}			
		);
	}

	// 文件/图片上传
	$scope.uploadFile=function(){
        uploadService.uploadFile().success(

            function (response) {
                if (response.success) {
                    $scope.image_entity.url=response.message;
                } else {
                    alert(response.message)
                }
            }
        ).error(function () {
			alert("上传错误")
        })
	}

	//图片列表
	$scope.entity={goods:{},goodsDesc:{itemImages:[],specificationItems:[]}}; //定义页面实体结构

	$scope.add_image_entity=function () {
		$scope.entity.goodsDesc.itemImages.push($scope.image_entity)
    }

    //移除图片
	$scope.remove_image_entity=function (index) {
		$scope.entity.goodsDesc.itemImages.splice(index,1);
    }

    //读取一级分类
	$scope.selectItemCat1List=function () {
		itemCatService.findByParentId(0).success(
			function (response) {
				$scope.itemCat1List=response;
            }
		)
    }

    //读取二级分类
	$scope.$watch('entity.goods.category1Id',function (newValue,oldValue) { //当变量 'entity.goods.category1Id' 变化后出发function()函数
		//根据选择的值,查询二级分类
		itemCatService.findByParentId(newValue).success(
			function (response) {
				$scope.itemCat2List=response;
            }
		)
    })

    //读取三级分类
    $scope.$watch('entity.goods.category2Id',function (newValue,oldValue) {
        //根据选择的值,查询二级分类
        itemCatService.findByParentId(newValue).success(
            function (response) {
                $scope.itemCat3List=response;
            }
        )
    })

	//三级分类选择后,读取模板id
    $scope.$watch('entity.goods.category3Id',function (newValue,oldValue) {
        //根据选择的值,查询二级分类
        itemCatService.findOne(newValue).success(
            function (response) {
                $scope.entity.goods.typeTemplateId=response.typeId;//更新模板id
            }
        )
    })

	//模板id选择后,根据模板id更新品牌下拉列表
	$scope.$watch('entity.goods.typeTemplateId',function (newValue, oldValue) {
		typeTemplateService.findOne(newValue).success(
			function (response) {
				$scope.typeTemplate=response;
                $scope.typeTemplate.brandIds=JSON.parse($scope.typeTemplate.brandIds);

                //扩展属性
				if ($location.search()['id'] == null){ //如果id为空则是增加商品

                    $scope.entity.goodsDesc.customAttributeItems=JSON.parse($scope.typeTemplate.customAttributeItems);
                }
            }
		);

		//查询规格列表
		typeTemplateService.findSpecList(newValue).success(
			function (response) {
				$scope.specList=response;
            }
		)
    })

	// [{"attributeName":"网络制式","attributeValue":["移动4G"]},{"attributeName":"屏幕尺寸","attributeValue":["5.5寸","4.5寸"]}]

	// 保存规格中选中的规格选项
	$scope.updateSpecAttribute=function ($event,name,value) {
		//获取specificationItems集合
		var object = $scope.searchObjectByKey($scope.entity.goodsDesc.specificationItems,'attributeName',name);

		if (object != null) { //如果attributeName不为空,直接添加attributeValue属性
			if ($event.target.checked) { //勾选

                object.attributeValue.push(value);

            }else { //取消勾选
                object.attributeValue.splice(object.attributeValue.indexOf(value),1)
			}
			//如果选项都取消了,直接移除此项
			if (object.attributeValue.length == 0) {
				$scope.entity.goodsDesc.specificationItems.splice($scope.entity.goodsDesc.specificationItems.indexOf(object),1)
			}

		}else { //如果attributeName为空,添加整组属性,{"attributeName":"网络制式","attributeValue":["移动4G"]}
			$scope.entity.goodsDesc.specificationItems.push({"attributeName":name,"attributeValue":[value]})
		}
    }

    //创建SKU列表
    $scope.createItemList=function () {
        $scope.entity.itemList=[{spec:{},price:0,num:9999,status:'0',isDefault:'0'}]; //初始化SKU列表

	    var items=$scope.entity.goodsDesc.specificationItems; //一个具体商品的规格集合

        for (var i = 0; i < items.length; i++) {
            $scope.entity.itemList=addColumn($scope.entity.itemList,items[i].attributeName,items[i].attributeValue);
        }
    }

    //添加列值
    addColumn=function (list, columnName, columnValues) { // list:拼接嵌套前的集合;columnName:列名称(如:网络制式);columnValues:列名称对应的属性集合(如:[2G,3G])
        var newList=[]; //新集合

        for (var i = 0; i < list.length; i++) {

            var oldRow=list[i];

            for (var j = 0; j < columnValues.length; j++) {
                var newRow= JSON.parse(JSON.stringify(oldRow));//克隆
                newRow.spec[columnName]=columnValues[j];
                newList.push(newRow);
            }
        }
        return newList;
    }

    //商品状态
	$scope.status=['未审核','审核通过','审核未通过','审核中'];

	//加载商品分类列表
	$scope.itemCatList=[];//定义前台商品分类列表集合
	$scope.findItemCatList=function () {
		itemCatService.findAll().success(
			function (response) {
                for (var i = 0; i < response.length; i++) {
                    $scope.itemCatList[response[i].id]=response[i].name; //将后台返回的集合中的name赋值给前台集合对应的下表
                }
            }
		)
    }

    //根据规格名称和规格选项名称返回是否被勾选
	$scope.checkAttributeValue=function (specName,optionName) {
        var items=$scope.entity.goodsDesc.specificationItems; //一个具体商品的规格集合

		var object=$scope.searchObjectByKey(items,'attributeName',specName);//从集合中按照key(attributeName)查询对象

		if (object != null) {
			if (object.attributeValue.indexOf(optionName) >= 0) { //如果能查询到规格选项
				return true;
			}else {
				return false;
			}
		}else {
			return false;
		}
    }

    //商品上下架

});
